package com.cskaoyan.market.controller;

import com.cskaoyan.market.db.domain.MarketCoupon;
import com.cskaoyan.market.service.MarketCouponService;
import com.cskaoyan.market.service.MarketCouponServiceImpl;
import com.cskaoyan.market.util.JacksonUtil;
import com.cskaoyan.market.util.ResponseUtil;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

@WebServlet("/admin/coupon/*")
public class AdminCouponController extends HttpServlet {
    private MarketCouponService marketCouponService = new MarketCouponServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String requestURI = req.getRequestURI();
        String op = requestURI.replace(req.getContextPath() + "/admin/coupon/", "");
        if ("list".equals(op)) {
            list(req, resp);
        } else if ("read".equals(op)) {
            read(req, resp);
        }
    }

    private void read(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String id = req.getParameter("id");
        MarketCoupon marketCoupon = marketCouponService.read(Integer.parseInt(id));
        resp.getWriter().println(JacksonUtil.getObjectMapper().writeValueAsString(ResponseUtil.ok(marketCoupon)));
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String requestURI = req.getRequestURI();
        String op = requestURI.replace(req.getContextPath() + "/admin/coupon/", "");
        if ("update".equals(op)) {
            update(req, resp);
        } else if ("create".equals(op)) {
            create(req, resp);
        } else if ("delete".equals(op)) {
            delete(req, resp);
        }
    }

    private void delete(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String requestBody = req.getReader().readLine();
        MarketCoupon marketCoupon = new MarketCoupon();
        String id = JacksonUtil.parseString(requestBody, "id");
        assert id != null;
        marketCoupon.setId(Integer.parseInt(id));
        marketCouponService.delete(marketCoupon);
        resp.getWriter().println(JacksonUtil.getObjectMapper().writeValueAsString(ResponseUtil.ok(marketCoupon)));
    }

    private void create(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String requestBody = req.getReader().readLine();
        MarketCoupon marketCoupon = new MarketCoupon();
        String name = JacksonUtil.parseString(requestBody, "name");
        String desc = JacksonUtil.parseString(requestBody, "desc");
        String tag = JacksonUtil.parseString(requestBody, "tag");
        String total = JacksonUtil.parseString(requestBody, "total");
        String discount = JacksonUtil.parseString(requestBody, "discount");
        String min = JacksonUtil.parseString(requestBody, "min");
        String limit = JacksonUtil.parseString(requestBody, "limit");
        String type = JacksonUtil.parseString(requestBody, "type");
        String status = JacksonUtil.parseString(requestBody, "status");
        String timeType = JacksonUtil.parseString(requestBody, "timeType");
        String days = JacksonUtil.parseString(requestBody, "days");
        String startTime = JacksonUtil.parseString(requestBody, "startTime");
        String endTime = JacksonUtil.parseString(requestBody, "endTime");
        marketCoupon.setName(name);
        marketCoupon.setDesc(desc);
        marketCoupon.setTag(tag);
        if (total != null) {
            marketCoupon.setTotal(Integer.parseInt(total));
        }
        if (discount != null) {
            marketCoupon.setDiscount(new BigDecimal(discount));
        }
        if (min != null) {
            marketCoupon.setMin(new BigDecimal(min));
        }
        if (limit != null) {
            marketCoupon.setLimit(Short.parseShort(limit));
        }
        if (type != null) {
            marketCoupon.setType(Short.parseShort(type));
        }
        if (status != null) {
            marketCoupon.setStatus(Short.parseShort(status));
        }
        assert timeType != null;
        short timeTypeShort = Short.parseShort(timeType);
        marketCoupon.setTimeType(timeTypeShort);
        if (timeTypeShort == 0) {
            marketCoupon.setDays(Short.parseShort(days != null ? days : "0"));
        } else {
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            LocalDateTime start = LocalDateTime.parse(startTime, formatter);
            LocalDateTime end = LocalDateTime.parse(endTime, formatter);
            marketCoupon.setStartTime(start);
            marketCoupon.setEndTime(end);
        }
        marketCoupon.setAddTime(LocalDateTime.now());
        marketCoupon.setUpdateTime(LocalDateTime.now());
        marketCouponService.create(marketCoupon);
        resp.getWriter().println(JacksonUtil.getObjectMapper().writeValueAsString(ResponseUtil.ok(marketCoupon)));

    }

    private void update(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String requestBody = req.getReader().readLine();
        MarketCoupon marketCoupon = new MarketCoupon();
        String id = JacksonUtil.parseString(requestBody, "id");
        String name = JacksonUtil.parseString(requestBody, "name");
        String desc = JacksonUtil.parseString(requestBody, "desc");
        String tag = JacksonUtil.parseString(requestBody, "tag");
        String total = JacksonUtil.parseString(requestBody, "total");
        String discount = JacksonUtil.parseString(requestBody, "discount");
        String min = JacksonUtil.parseString(requestBody, "min");
        String limit = JacksonUtil.parseString(requestBody, "limit");
        String type = JacksonUtil.parseString(requestBody, "type");
        String status = JacksonUtil.parseString(requestBody, "status");
        String timeType = JacksonUtil.parseString(requestBody, "timeType");
        String days = JacksonUtil.parseString(requestBody, "days");
        String startTime = JacksonUtil.parseString(requestBody, "startTime");
        String endTime = JacksonUtil.parseString(requestBody, "endTime");
        assert id != null;
        marketCoupon.setId(Integer.parseInt(id));
        marketCoupon.setName(name);
        marketCoupon.setDesc(desc);
        marketCoupon.setTag(tag);
        if (total != null) {
            marketCoupon.setTotal(Integer.parseInt(total));
        }
        if (discount != null) {
            marketCoupon.setDiscount(new BigDecimal(discount));
        }
        if (min != null) {
            marketCoupon.setMin(new BigDecimal(min));
        }
        if (limit != null) {
            marketCoupon.setLimit(Short.parseShort(limit));
        }
        if (type != null) {
            marketCoupon.setType(Short.parseShort(type));
        }
        if (status != null) {
            marketCoupon.setStatus(Short.parseShort(status));
        }
        assert timeType != null;
        short timeTypeShort = Short.parseShort(timeType);
        marketCoupon.setTimeType(timeTypeShort);
        if (timeTypeShort == 0) {
            marketCoupon.setDays(Short.parseShort(days != null ? days : "0"));
        } else {
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            LocalDateTime start = LocalDateTime.parse(startTime, formatter);
            LocalDateTime end = LocalDateTime.parse(endTime, formatter);
            marketCoupon.setStartTime(start);
            marketCoupon.setEndTime(end);
        }
        marketCoupon.setUpdateTime(LocalDateTime.now());
        marketCouponService.update(marketCoupon);
        resp.getWriter().println(JacksonUtil.getObjectMapper().writeValueAsString(ResponseUtil.ok(marketCoupon)));
    }

    private void list(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //接收用户提交过来的请求参数信息
        String pageParam = req.getParameter("page");
        String limitParam = req.getParameter("limit");
        String name = req.getParameter("name");
        String typeParam = req.getParameter("type");
        String statusParam = req.getParameter("status");
        String sort = req.getParameter("sort");
        String order = req.getParameter("order");
        Integer page = null;
        Integer limit = null;
        Short type = null;
        Short status = null;
        try {
            page = Integer.parseInt(pageParam);
            limit = Integer.parseInt(limitParam);
            if (!StringUtils.isEmpty(typeParam)) {
                type = Short.parseShort(typeParam);
            }
            if (!StringUtils.isEmpty(statusParam)) {
                status = Short.parseShort(statusParam);
            }
        } catch (NumberFormatException e) {
            Object object = ResponseUtil.badArgument();
            String s = JacksonUtil.getObjectMapper().writeValueAsString(object);
            resp.getWriter().println(s);
            return;
        }
        List<MarketCoupon> marketCouponsList = marketCouponService.list(limit, page, name, type, status, sort, order);
        Object o = ResponseUtil.okList(marketCouponsList);
        resp.getWriter().println(JacksonUtil.getObjectMapper().writeValueAsString(o));
    }
}
